package com.whq.knowverywell.activity;

import java.util.ArrayList;
import java.util.List;

import android.R.color;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.whq.knowverywell.R;
import com.whq.knowverywell.adapter.ContentListAdapter;
import com.whq.knowverywell.adapter.DetailListAdapter;
import com.whq.knowverywell.business.http.model.BaseSalesReturn;
import com.whq.knowverywell.business.http.model.ProductSalesReturn;
import com.whq.knowverywell.business.http.model.RegionSalesReturn;
import com.whq.knowverywell.business.http.model.StoreSalseReturn;
import com.whq.knowverywell.business.model.BaseSalesRecord;
import com.whq.knowverywell.business.model.ProductSalesRecord;
import com.whq.knowverywell.business.model.PropertySalesRecord;
import com.whq.knowverywell.business.model.RegionSalesRecord;
import com.whq.knowverywell.business.model.StoreSalesRecord;
import com.whq.knowverywell.task.DomainDetailTask;
import com.whq.knowverywell.task.DomainTask;
import com.whq.knowverywell.task.HotSellTask;
import com.whq.knowverywell.task.HotsellDetailTask;
import com.whq.knowverywell.task.SortDetailTask;
import com.whq.knowverywell.task.SortTask;
import com.whq.knowverywell.task.SummaryDetailTask;
import com.whq.knowverywell.task.SummaryTask;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.TipUtil;
import com.whq.knowverywell.util.constant.CfgConstant;
import com.whq.knowverywell.util.constant.ModelConstant;
import com.whq.knowverywell.util.constant.ParamConstant;
import com.whq.knowverywell.view.XListView;
import com.whq.knowverywell.view.XListView.IXListViewListener;

/**
 * content
 * 
 * @author daiwei
 *
 */
public final class ContentFragment extends SherlockFragment implements  HotsellDetailTask.DetailResultDataListener, DomainDetailTask.DetailResultDataListener, SortDetailTask.DetailResultDataListener, SummaryDetailTask.DetailResultDataListener, HotSellTask.ResultDataListener, SortTask.ResultDataListener, SummaryTask.ResultDataListener,DomainTask.ResultDataListener, IXListViewListener, OnItemClickListener {
	private static final String TAG = ContentFragment.class.getSimpleName();
    private static final String KEY_CONTENT = "ContentFragment:Content";

    public static ContentFragment newInstance(int durationType, int businessType, int fragmentType) {
        ContentFragment fragment = new ContentFragment();
        LogUtil.i(TAG, "----------------- fragment id [" + fragment.getId() + "]" + "fragment tag [" + fragment.getTag() + "]");
        fragment.durationType = durationType;
        fragment.businessType = businessType;
        fragment.fragmentType = fragmentType;
        LogUtil.i(TAG, "parameters durationType[" + durationType + "] businessType[" + businessType + "] fragmentType[" + fragmentType + "]");

        return fragment;
    }

    private String mContent = "数据加载中 ...";
    // ------ content fragment -----------------
    private List<StoreSalesRecord> mSummaryList = new ArrayList<StoreSalesRecord>();
    private SummaryTask mSummaryTask;
    private List<RegionSalesRecord> mDomainList = new ArrayList<RegionSalesRecord>();
    private DomainTask mDomainTask;
    private List<PropertySalesRecord> mSortList = new ArrayList<PropertySalesRecord>();
    private SortTask mSortTask;
    private List<ProductSalesRecord> mHotsellList = new ArrayList<ProductSalesRecord>();
    private HotSellTask mHotsellTask;
    // ----- end content fragment --------------
    
    // ------ detail fragment ------------------
    private List<ProductSalesRecord> mSummaryDetailList = new ArrayList<ProductSalesRecord>();
    private SummaryDetailTask mSummaryDetailTask;
    private List<ProductSalesRecord> mSortDetailList = new ArrayList<ProductSalesRecord>();
    private SortDetailTask mSortDetailTask;
    private List<StoreSalesRecord> mDomainDetailList = new ArrayList<StoreSalesRecord>();
    private DomainDetailTask mDomainDetailTask;
    private List<ProductSalesRecord> mHotsellDetailList = new ArrayList<ProductSalesRecord>();
    private HotsellDetailTask mHotsellDetailTask;
    // ------ end detail fragment --------------
    
    private XListView mXlistView;
    private TextView mPromptTextView;
    private BaseAdapter mListAdapter;
    private OnSumDataListener mListener;
    
    // yesterday, today, current month, current year
    private int durationType;
    // statics , detail
    private int fragmentType;
    // summary, domain, sort, hotsell
    private int businessType;
    private int pageNo = 1;
    private String productNo;
    private String orderBy = "";
    
    @Override
    public void onAttach(Activity activity) {
    	LogUtil.d(TAG, "onAttach start ...");
    	super.onAttach(activity);
    	
    	try {
			mListener = (OnSumDataListener) activity;
			productNo = mListener.getProductNo();
		} catch (ClassCastException e) {
			LogUtil.e(TAG, "activity dont implements OnSumDataListener interface .", e);
		}
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    	LogUtil.d(TAG, "onCreate start ...");
        super.onCreate(savedInstanceState);

        if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
            mContent = savedInstanceState.getString(KEY_CONTENT);
        }
        
        setHasOptionsMenu(true);
        
        getSherlockActivity().getSupportActionBar().setBackgroundDrawable(getResources().getDrawable(R.drawable.top_menu_bg));
        LogUtil.i(TAG, "action bar height[" + getSherlockActivity().getSupportActionBar().getHeight() + "]");
        getSherlockActivity().getSupportActionBar().setDisplayShowHomeEnabled(false);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    	LogUtil.d(TAG, "onCreateView start ...");
    	Bundle paramBundle = getArguments();
    	if (paramBundle != null) {
    		durationType = paramBundle.getInt(ParamConstant.BUNDLE_KEY_DURATION_TYPE);
    	}
    	
    	mPromptTextView = new TextView(getSherlockActivity());
    	mPromptTextView.setGravity(Gravity.CENTER);
    	mPromptTextView.setText(mContent);
    	mPromptTextView.setTextColor(Color.WHITE);
    	mPromptTextView.setTextSize(10 * getResources().getDisplayMetrics().density);
    	mPromptTextView.setPadding(20, 20, 20, 20);
    	mPromptTextView.setVisibility(View.VISIBLE);
        
        mXlistView = new XListView(getSherlockActivity());
        mXlistView.setPullLoadEnable(true);
        mXlistView.setPullRefreshEnable(false);
        mXlistView.setXListViewListener(this);
        mXlistView.setBackgroundColor(color.white);
        mXlistView.setDivider(getResources().getDrawable(R.drawable.content_list_dash));
        switch (businessType) {
		case ModelConstant.BUSINESS_TYPE_SUMMARY:
			if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
				mListAdapter = new ContentListAdapter(getSherlockActivity(), mSummaryList, businessType, this.durationType);
			} else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
				mListAdapter = new DetailListAdapter(getSherlockActivity(), mSummaryDetailList, businessType);
				mXlistView.setBackgroundColor(Color.parseColor("#ecf5f8"));
			}
			break;
			
		case ModelConstant.BUSINESS_TYPE_DOMAIN:
			if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
			    mListAdapter = new ContentListAdapter(getSherlockActivity(), mDomainList, businessType, this.durationType);
            } else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
                mListAdapter = new ContentListAdapter(getSherlockActivity(), mDomainDetailList, ModelConstant.BUSINESS_TYPE_SUMMARY, this.durationType);
            } 
			break;
			
		case ModelConstant.BUSINESS_TYPE_SORT:
			if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
				mListAdapter = new ContentListAdapter(getSherlockActivity(), mSortList, businessType, this.durationType);
			} else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
				mListAdapter = new DetailListAdapter(getSherlockActivity(), mSortDetailList, businessType);
				mXlistView.setBackgroundColor(Color.parseColor("#ecf5f8"));
			}
			break;
			
		case ModelConstant.BUSINESS_TYPE_HOTSELL:
			if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
			    mListAdapter = new DetailListAdapter(getSherlockActivity(), mHotsellList, businessType);
	            mXlistView.setBackgroundColor(Color.parseColor("#ecf5f8"));
            } else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
                mListAdapter = new DetailListAdapter(getSherlockActivity(), mHotsellDetailList, businessType);
                mXlistView.setBackgroundColor(Color.parseColor("#ecf5f8"));
            }
			break;

		default:
			break;
		}
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setVisibility(View.GONE);
        
        FrameLayout layout = new FrameLayout(getSherlockActivity());
        layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        layout.addView(mPromptTextView);
        layout.addView(mXlistView);
        
        refreshData();
        
        return layout;
    }
    
    @Override
    public void onResume() {
    	LogUtil.d(TAG, "onResume start ...");
    	super.onResume();
    	
//    	refreshData();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
    	LogUtil.d(TAG, "onSaveInstanceState start ...");
        super.onSaveInstanceState(outState);
        outState.putString(KEY_CONTENT, mContent);
    }

	@Override
	public void handleData(StoreSalseReturn huizongResult) {
		LogUtil.d(TAG, "handleData summary data start ...");
		mXlistView.stopLoadMore();
		mXlistView.stopRefresh();
		
		if (huizongResult == null) {
			mPromptTextView.setText("数据加载异常，请稍后重试。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		List<StoreSalesRecord> huizongList = huizongResult.getRecordList();
		
		if ((huizongList == null || huizongList.size() == 0) && (mSummaryList == null || mSummaryList.size() == 0)) {
			LogUtil.w(TAG, "summary is null . ");
			mPromptTextView.setText("没有可以显示的数据。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		//endCode = !StringUtil.isEmpty(huizongResult.getEndCode())?huizongResult.getEndCode():endCode;
		pageNo++;
		int oldSelection = mSummaryList.size();
		mSummaryList.addAll(huizongList);
		mListAdapter = new ContentListAdapter(getSherlockActivity(), mSummaryList, businessType, this.durationType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setSelection(oldSelection);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        if (mSummaryTask != null) {
        	mSummaryTask.cancel(true);
        	mSummaryTask = null;
        }
        if (huizongList.size() < CfgConstant.PAGE_COUNT) {
            mXlistView.setPullLoadEnable(false);
        } else {
            mXlistView.setPullLoadEnable(true);
        }
        
        mListener.onSumData(durationType, huizongResult.getTotalSalesVolume(), huizongResult.getTotalSalesAmount());
	}
	
	@Override
	public void handleData(RegionSalesReturn domainResult) {
		LogUtil.d(TAG, "handleData domain data start ...");
		mXlistView.stopLoadMore();
		mXlistView.stopRefresh();
		
		if (domainResult == null) {
			mPromptTextView.setText("数据加载异常，请稍后重试。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		List<RegionSalesRecord> domainList = domainResult.getRecordList();
		
		if ((domainList == null || domainList.size() == 0) && (mDomainList == null || mDomainList.size() == 0)) {
			LogUtil.w(TAG, "domain is null . ");
			mPromptTextView.setText("没有可以显示的数据。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		//endCode = !StringUtil.isEmpty(domainResult.getEndCode())?domainResult.getEndCode():endCode;
		pageNo++;
		int oldSelection = mDomainList.size();
		mDomainList.addAll(domainList);
		mListAdapter = new ContentListAdapter(getSherlockActivity(), mDomainList, businessType, this.durationType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setSelection(oldSelection);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        if (mDomainTask != null) {
        	mDomainTask.cancel(true);
        	mDomainTask = null;
        }
        if (domainList.size() < CfgConstant.PAGE_COUNT) {
            mXlistView.setPullLoadEnable(false);
        } else {
            mXlistView.setPullLoadEnable(true);
        }
        
        mListener.onSumData(durationType, domainResult.getTotalSalesVolume(), domainResult.getTotalSalesAmount());
	}
	
	@Override
	public void handleData(BaseSalesReturn<BaseSalesRecord> result) {
		LogUtil.d(TAG, "handleData sort data start ...");
		
		mXlistView.stopLoadMore();
		mXlistView.stopRefresh();
		
		if (result == null) {
			mPromptTextView.setText("数据加载异常，请稍后重试。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		List resultList = result.getRecordList();
		
		if ((resultList == null || resultList.size() == 0) && (mSortList == null || mSortList.size() == 0)) {
			LogUtil.w(TAG, "sort is null . ");
			mPromptTextView.setText("没有可以显示的数据。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		//endCode = !StringUtil.isEmpty(result.getEndCode())?result.getEndCode():endCode;
		pageNo++;
		int oldSelection = mSortList.size();
		mSortList.addAll(resultList);
		mListAdapter = new ContentListAdapter(getSherlockActivity(), mSortList, businessType, this.durationType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setSelection(oldSelection);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        if (mSortTask != null) {
        	mSortTask.cancel(true);
        	mSortTask = null;
        }
        if (resultList.size() < CfgConstant.PAGE_COUNT) {
            mXlistView.setPullLoadEnable(false);
        } else {
            mXlistView.setPullLoadEnable(true);
        }
        
        mListener.onSumData(durationType, result.getTotalSalesVolume(), result.getTotalSalesAmount());
	}
	
	@Override
	public void handleData(ProductSalesReturn hotSellResult) {
		LogUtil.d(TAG, "handleData hotsell data start ...");
		mXlistView.stopLoadMore();
		mXlistView.stopRefresh();
		
		if (hotSellResult == null) {
			mPromptTextView.setText("数据加载异常，请稍后重试。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		List<ProductSalesRecord> hotSellList = hotSellResult.getRecordList();
		
		if ((hotSellList == null || hotSellList.size() == 0) && (mHotsellList == null || mHotsellList.size() == 0)) {
			LogUtil.w(TAG, "hotsell is null . ");
			mPromptTextView.setText("没有可以显示的数据。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		//endCode = !StringUtil.isEmpty(hotSellResult.getEndCode())?hotSellResult.getEndCode():endCode;
		pageNo++;
		int oldSelection = mHotsellList.size();
		mHotsellList.addAll(hotSellList);
		mListAdapter = new DetailListAdapter(getSherlockActivity(), mHotsellList, businessType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setSelection(oldSelection);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        if (mHotsellTask != null) {
        	mHotsellTask.cancel(true);
        	mHotsellTask = null;
        }
        if (hotSellList.size() < CfgConstant.PAGE_COUNT) {
            mXlistView.setPullLoadEnable(false);
        } else {
            mXlistView.setPullLoadEnable(true);
        }
        
        mListener.onSumData(durationType, hotSellResult.getTotalSalesVolume(), hotSellResult.getTotalSalesAmount());
	}
	
	@Override
	public void handleDetailData(ProductSalesReturn detailResult) {
		LogUtil.d(TAG, "handleDetailData summary detail data start ...");
		mXlistView.stopLoadMore();
		mXlistView.stopRefresh();
		
		if (detailResult == null) {
			mPromptTextView.setText("数据加载异常，请稍后重试。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		List<ProductSalesRecord> summaryDetailList = detailResult.getRecordList();
		
		if ((summaryDetailList == null || summaryDetailList.size() == 0) && (mSummaryDetailList == null || mSummaryDetailList.size() == 0)) {
            LogUtil.w(TAG, "summary detail is null . ");
            mPromptTextView.setText("没有可以显示的数据。");
            mXlistView.setVisibility(View.GONE);
            mPromptTextView.setVisibility(View.VISIBLE);
            return;
        }
        
        //endCode = !StringUtil.isEmpty(detailResult.getEndCode())?detailResult.getEndCode():endCode;
		pageNo++;
		int oldSelection = mSummaryDetailList.size();
        mSummaryDetailList.addAll(summaryDetailList);
        mListAdapter = new DetailListAdapter(getSherlockActivity(), mSummaryDetailList, businessType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setSelection(oldSelection);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        if (mSummaryTask != null) {
        	mSummaryTask.cancel(true);
        	mSummaryTask = null;
        }
        if (summaryDetailList.size() < CfgConstant.PAGE_COUNT) {
            mXlistView.setPullLoadEnable(false);
        } else {
            mXlistView.setPullLoadEnable(true);
        }
        
        mListener.onSumData(durationType, detailResult.getTotalSalesVolume(), detailResult.getTotalSalesAmount());
	}
	
	@Override
	public void handleSortDetailData(ProductSalesReturn detailResult) {
		LogUtil.d(TAG, "handleSortDetailData start ...");
		mXlistView.stopLoadMore();
		mXlistView.stopRefresh();
		
		if (detailResult == null) {
			mPromptTextView.setText("数据加载异常，请稍后重试。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		List<ProductSalesRecord> sortDetailList = detailResult.getRecordList();
		
		if ((sortDetailList == null || sortDetailList.size() == 0) && (mSortDetailList == null || mSortDetailList.size() == 0)) {
			LogUtil.w(TAG, "sort detail is null . ");
			mPromptTextView.setText("没有可以显示的数据。");
			mXlistView.setVisibility(View.GONE);
			mPromptTextView.setVisibility(View.VISIBLE);
			return;
		}
		
		//endCode = !StringUtil.isEmpty(detailResult.getEndCode())?detailResult.getEndCode():endCode;
		pageNo++;
		int oldSelection = mSortDetailList.size();
		mSortDetailList.addAll(sortDetailList);
		mListAdapter = new DetailListAdapter(getSherlockActivity(), mSortDetailList, businessType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setSelection(oldSelection);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        if (mSortDetailTask != null) {
        	mSortDetailTask.cancel(true);
        	mSortDetailTask = null;
        }
        if (sortDetailList.size() < CfgConstant.PAGE_COUNT) {
            mXlistView.setPullLoadEnable(false);
        } else {
            mXlistView.setPullLoadEnable(true);
        }
        
        mListener.onSumData(durationType, detailResult.getTotalSalesVolume(), detailResult.getTotalSalesAmount());
	}
	
	@Override
    public void handleDomainDetailData(StoreSalseReturn domainDetailResult) {
	    LogUtil.d(TAG, "handleDomainDetailData start ...");
        mXlistView.stopLoadMore();
        mXlistView.stopRefresh();
        
        if (domainDetailResult == null) {
            mPromptTextView.setText("数据加载异常，请稍后重试。");
            mXlistView.setVisibility(View.GONE);
            mPromptTextView.setVisibility(View.VISIBLE);
            return;
        }
        
        List<StoreSalesRecord> domainDetailList = domainDetailResult.getRecordList();
        
        if ((domainDetailList == null || domainDetailList.size() == 0) && (mDomainDetailList == null || mDomainDetailList.size() == 0)) {
            LogUtil.w(TAG, "domain detail is null . ");
            mPromptTextView.setText("没有可以显示的数据。");
            mXlistView.setVisibility(View.GONE);
            mPromptTextView.setVisibility(View.VISIBLE);
            return;
        }
        //endCode = !StringUtil.isEmpty(domainDetailResult.getEndCode())?domainDetailResult.getEndCode():endCode;
        pageNo++;
        int oldSelection = mDomainDetailList.size();
        mDomainDetailList.addAll(domainDetailList);
        LogUtil.i(TAG, "businessType: " + businessType);
        mListAdapter = new ContentListAdapter(getSherlockActivity(), mDomainDetailList, ModelConstant.BUSINESS_TYPE_SUMMARY, this.durationType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setSelection(oldSelection);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        if (mDomainDetailTask != null) {
            mDomainDetailTask.cancel(true);
            mDomainDetailTask = null;
        }
        if (domainDetailList.size() < CfgConstant.PAGE_COUNT) {
            mXlistView.setPullLoadEnable(false);
        } else {
            mXlistView.setPullLoadEnable(true);
        }
        
        mListener.onSumData(durationType, domainDetailResult.getTotalSalesVolume(), domainDetailResult.getTotalSalesAmount());
    }
	
	@Override
    public void handleHotsellDetailData(ProductSalesReturn hotsellDetailResult) {
	    LogUtil.d(TAG, "handleHotsellDetailData start ...");
        mXlistView.stopLoadMore();
        mXlistView.stopRefresh();
        
        if (hotsellDetailResult == null) {
            mPromptTextView.setText("数据加载异常，请稍后重试。");
            mXlistView.setVisibility(View.GONE);
            mPromptTextView.setVisibility(View.VISIBLE);
            return;
        }
        
        List<ProductSalesRecord> hotsellDetailList = hotsellDetailResult.getRecordList();
        
        if ((hotsellDetailList == null || hotsellDetailList.size() == 0) && (mHotsellDetailList == null || mHotsellDetailList.size() == 0)) {
            LogUtil.w(TAG, "hotsell detail is null . ");
            mPromptTextView.setText("没有可以显示的数据。");
            mXlistView.setVisibility(View.GONE);
            mPromptTextView.setVisibility(View.VISIBLE);
            return;
        }
        
        //endCode = !StringUtil.isEmpty(hotsellDetailResult.getEndCode())?hotsellDetailResult.getEndCode():endCode;
        pageNo++;
        int oldSelection = mHotsellDetailList.size();
        mHotsellDetailList.addAll(hotsellDetailList);
        mListAdapter = new DetailListAdapter(getSherlockActivity(), mHotsellDetailList, businessType);
        mXlistView.setAdapter(mListAdapter);
        mXlistView.setSelection(oldSelection);
        mXlistView.setVisibility(View.VISIBLE);
        mXlistView.setOnItemClickListener(this);
        mPromptTextView.setVisibility(View.GONE);
        if (mHotsellDetailTask != null) {
            mHotsellDetailTask.cancel(true);
            mHotsellDetailTask = null;
        }
        if (hotsellDetailList.size() < CfgConstant.PAGE_COUNT) {
            mXlistView.setPullLoadEnable(false);
        } else {
            mXlistView.setPullLoadEnable(true);
        }
        
        mListener.onSumData(durationType, hotsellDetailResult.getTotalSalesVolume(), hotsellDetailResult.getTotalSalesAmount());
    }
	
	public interface OnSumDataListener {
	    
		public void onSumData(int durationType, long totalSalesVolume, double totalSalesAmount);
		
		public String getProductNo();
		
		public void showSortPopupWindow(View anchor);
		
		public void showManagerPopupWindow(View anchor);
		
	}

	@Override
	public void onRefresh() {
		LogUtil.d(TAG, "onRefresh start ...");
		
	}

	@Override
	public void onLoadMore() {
		LogUtil.d(TAG, "onLoadMore start ...");
		
		switch (businessType) {
		case ModelConstant.BUSINESS_TYPE_SUMMARY:
			if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
				mSummaryTask = new SummaryTask(getSherlockActivity(), this, durationType);
		        mSummaryTask.execute(new String[]{orderBy, pageNo + ""});
			} else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
				mSummaryDetailTask = new SummaryDetailTask(getSherlockActivity(), this, durationType, productNo);
				mSummaryDetailTask.execute(new String[]{orderBy, pageNo + ""});
			}
			
			break;
			
		case ModelConstant.BUSINESS_TYPE_DOMAIN:
		    if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
		        mDomainTask = new DomainTask(getSherlockActivity(), this, durationType);
	            mDomainTask.execute(new String[]{orderBy, pageNo + ""});
            } else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
                mDomainDetailTask = new DomainDetailTask(getSherlockActivity(), this, durationType, productNo);
                mDomainDetailTask.execute(new String[]{orderBy, pageNo + ""});
            }
			
			break;
			
		case ModelConstant.BUSINESS_TYPE_SORT:
			if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
				mSortTask = new SortTask(getSherlockActivity(), this, durationType);
				mSortTask.execute(new String[]{orderBy, pageNo + ""});
			} else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
				mSortDetailTask = new SortDetailTask(getSherlockActivity(), this, durationType, productNo);
				mSortDetailTask.execute(new String[]{orderBy, pageNo + ""});
			}
			break;
			
		case ModelConstant.BUSINESS_TYPE_HOTSELL:
			mHotsellTask = new HotSellTask(getSherlockActivity(), this, durationType);
			mHotsellTask.execute(new String[]{orderBy, pageNo + ""});
			break;

		default:
			break;
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View convertView, int position, long id) {
		LogUtil.d(TAG, "onItemClick position[" + position + "] id[" + id + "]");
		// content fragment support click
		if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
			Object obj = mListAdapter.getItem(position-1);
			Intent intent = new Intent();
			intent.setClass(getSherlockActivity(), ContentFrameActivity.class);
			intent.putExtra(ParamConstant.BUNDLE_KEY_FRAGMENT_TYPE, ModelConstant.FRAGEMENT_TYPE_DETAIL);
			intent.putExtra(ParamConstant.BUNDLE_KEY_ITEM_ID, businessType);
			
			if (obj instanceof ProductSalesRecord) {
				ProductSalesRecord productSalesRecord = (ProductSalesRecord) obj;
				intent.putExtra(ParamConstant.BUNDLE_KEY_PRODUCT_NO, productSalesRecord.getCode());
				intent.putExtra(ParamConstant.BUNDLE_KEY_FRAGMENT_TITLE, productSalesRecord.getName());
			} else if (obj instanceof RegionSalesRecord) {
				RegionSalesRecord regionSalesRecord = (RegionSalesRecord) obj;
				intent.putExtra(ParamConstant.BUNDLE_KEY_PRODUCT_NO, regionSalesRecord.getCode());
				intent.putExtra(ParamConstant.BUNDLE_KEY_FRAGMENT_TITLE, regionSalesRecord.getName());
			} else if (obj instanceof PropertySalesRecord) {
				PropertySalesRecord propertySalesRecord = (PropertySalesRecord) obj;
				intent.putExtra(ParamConstant.BUNDLE_KEY_PRODUCT_NO, propertySalesRecord.getCode());
				intent.putExtra(ParamConstant.BUNDLE_KEY_FRAGMENT_TITLE, propertySalesRecord.getName());
			} else if (obj instanceof StoreSalesRecord) {
				StoreSalesRecord storeSalesRecord = (StoreSalesRecord) obj;
				intent.putExtra(ParamConstant.BUNDLE_KEY_PRODUCT_NO, storeSalesRecord.getCode());
				intent.putExtra(ParamConstant.BUNDLE_KEY_FRAGMENT_TITLE, storeSalesRecord.getName());
			} else if (obj instanceof BaseSalesRecord) {
				BaseSalesRecord baseSalesRecord = (BaseSalesRecord) obj;
				intent.putExtra(ParamConstant.BUNDLE_KEY_PRODUCT_NO, baseSalesRecord.getCode());
				intent.putExtra(ParamConstant.BUNDLE_KEY_FRAGMENT_TITLE, baseSalesRecord.getName());
			} else {
				TipUtil.tipDescription(getSherlockActivity(), "onItemClick position[" + position + "] id[" + id + "]");
				return;
			}
			
			startActivity(intent);
		}
		
	}
	
	
	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		LogUtil.d(TAG, "onCreateOptionsMenu start ...");
		
		SubMenu sub1 = menu.addSubMenu("排序");
		sub1.setIcon(R.drawable.top_sort_n);
		sub1.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        
        SubMenu sub2 = menu.addSubMenu("刷新");
        sub2.setIcon(R.drawable.top_refresh_n);
        sub2.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        
        SubMenu sub = menu.addSubMenu("管理");
        sub.setIcon(R.drawable.btn_set);
        sub.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		LogUtil.d(TAG, "onOptionsItemSelected start ...");
		
		String menuItemTitle = item.getTitle().toString();
		LogUtil.d(TAG, "item id is : " + item.getItemId() + " title is : " + menuItemTitle);
		
		if (item.getItemId() == android.R.id.home || item.getItemId() == 0) {
		    if ("排序".equals(menuItemTitle)) {
		        doSort();
		    } else if ("管理".equals(menuItemTitle)) {
		        doManager();
		    } else {
		        doRefresh(); 
		    }
		    
            return true;
        }
        //Toast.makeText(getSherlockActivity(), "Theme changed to \"" + item.getTitle() + "\"", Toast.LENGTH_SHORT).show();
        return true;
	}

	// ------- customize method -------------
	/**
     * 刷新按钮按下
     */
    protected void doRefresh() {
        refreshData();
    }
    
    /**
     * 选中排序项
     */
    protected void doSort(String orderBy) {
    	this.orderBy = orderBy;
    	LogUtil.i(TAG, "order by key [" + this.orderBy + "]");
        refreshData();
    }
    
    /**
     * 排序按钮按下
     */
    protected void doSort() {
        mListener.showSortPopupWindow(null);
    }
    
    /**
     * 管理按钮按下
     */
    protected void doManager() {
        mListener.showManagerPopupWindow(null);
    }
    
    /**
     * 回滚列表到第一行
     */
    protected void scrollListViewOfFragment2Top() {
        if (mXlistView == null || mListAdapter.getCount() == 0) {
            return;
        }
        
        mXlistView.setSelection(0);
    }
    
    /**
     * 刷新数据
     */
    private void refreshData() {
        //endCode = "";
    	pageNo = 1;
        mPromptTextView.setText(mContent);
        mXlistView.setVisibility(View.GONE);
        mPromptTextView.setVisibility(View.VISIBLE);
        
        switch (businessType) {
        case ModelConstant.BUSINESS_TYPE_SUMMARY:
            if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
                mSummaryList.clear();
                mSummaryTask = new SummaryTask(getSherlockActivity(), this, durationType);
                mSummaryTask.execute(new String[]{orderBy, pageNo + ""});
            } else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
                mSummaryDetailList.clear();
                mSummaryDetailTask = new SummaryDetailTask(getSherlockActivity(), this, durationType, productNo);
                mSummaryDetailTask.execute(new String[]{orderBy, pageNo + ""});
            }
            
            break;
            
        case ModelConstant.BUSINESS_TYPE_DOMAIN:
            
            
            if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
                mDomainList.clear();
                mDomainTask = new DomainTask(getSherlockActivity(), this, durationType);
                mDomainTask.execute(new String[]{orderBy, pageNo + ""});
            } else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
                mDomainDetailList.clear();
                mDomainDetailTask = new DomainDetailTask(getSherlockActivity(), this, durationType, productNo);
                mDomainDetailTask.execute(new String[]{orderBy, pageNo + ""});
            } 
            
            break;
            
        case ModelConstant.BUSINESS_TYPE_SORT:
            if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
                mSortList.clear();
                mSortTask = new SortTask(getSherlockActivity(), this, durationType);
                mSortTask.execute(new String[]{orderBy, pageNo + ""});
            } else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
                mSortDetailList.clear();
                mSortDetailTask = new SortDetailTask(getSherlockActivity(), this, durationType, productNo);
                mSortDetailTask.execute(new String[]{orderBy, pageNo + ""});
            }
            break;
            
        case ModelConstant.BUSINESS_TYPE_HOTSELL:
            if (fragmentType == ModelConstant.FRAGEMENT_TYPE_CONTENT) {
                mHotsellList.clear();
                mHotsellTask = new HotSellTask(getSherlockActivity(), this, durationType);
                mHotsellTask.execute(new String[]{orderBy, pageNo + ""});
            } else if (fragmentType == ModelConstant.FRAGEMENT_TYPE_DETAIL) {
                mHotsellDetailList.clear();
                mHotsellDetailTask = new HotsellDetailTask(getSherlockActivity(), this, durationType, productNo);
                mHotsellDetailTask.execute(new String[]{orderBy, pageNo + ""});
            }
            break;

        default:
            break;
        }
    }
}
